package org.anyin.gitee.cloud.lib.permission;

import cn.dev33.satoken.stp.StpInterface;
import org.anyin.gitee.cloud.lib.core.utils.CollectionUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StpInterfaceImpl implements StpInterface , ClearPermissionRoleService{

    private final PermissionRoleService permissionService;

    public StpInterfaceImpl(PermissionRoleService permissionService) {
        this.permissionService = permissionService;
    }

    private final Map<String, List<String>> loginIdToPermissionMap = new HashMap<>();

    private final Map<String, List<String>> loginIdToRoleMap = new HashMap<>();

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> permissions = loginIdToPermissionMap.get((String) loginId);
        if(CollectionUtil.isEmpty(permissions)){
            permissions = permissionService.getPermissionByLoginId((String) loginId);
            loginIdToPermissionMap.put((String) loginId, permissions);
        }
        return permissions;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roles = loginIdToRoleMap.get((String) loginId);
        if(CollectionUtil.isEmpty(roles)){
            roles = permissionService.getRoleByLoginId((String) loginId);
            loginIdToRoleMap.put((String) loginId, roles);
        }
        return roles;
    }

    @Override
    public void clear(String loginId) {
        loginIdToPermissionMap.remove(loginId);
        loginIdToRoleMap.remove(loginId);
    }
}
